<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useInitTable } from '@/hooks/useTable'
import { getRoleListAPI } from '@/api/role'
import {
  getAdminListAPI,
  addAdminAPI,
  updateAdminAPI,
  deleteAdminAPI,
  updateUserRoleAPI
} from '@/api/admin'

// 处理响应结果
const handleSuccess = (result) => {
  tableData.value = result.rows.map((item) => {
    item.btnLoading = false
    return item
  })
  total.value = result.count
}
// 列表 | 分页 | 搜索 | 多选 | 删除
const tableOptions = {
  params: {
    page: 1,
    pageSize: 10,
    username: null,
    type: 0
  },
  getDataAPI: getAdminListAPI,
  deleteAPI: deleteAdminAPI,
  onSuccess: handleSuccess
}
const {
  params,
  tableData,
  tableLoading,
  total,
  multiSelection,
  getData,
  handleSearch,
  handleSelectionChange,
  handleBatchDelete,
  handleDelete,
  handleIndex
} = useInitTable(tableOptions)

// 添加 | 修改
const avatarRef = ref(null)
const addForm = ref({})
const formRef = ref(null)
const dialogVisible = ref(false)
const btnLoading = ref(false)
const addFormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '输入密码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'blur' }]
}
// 打开弹窗
const handleOpenDialog = (row) => {
  addForm.value = row
  formRef.value?.resetFields()
  dialogVisible.value = true
}
// 添加
const handleAdd = () => {
  avatarRef.value?.reset()
  handleOpenDialog({ username: '', password: '', avatar: '-1', type: 1 })
}
// 修改
const handleEdit = (row) => {
  handleOpenDialog({ id: row.id, avatar: row.avatar, type: row.type })
}
const isAdd = computed(() => !Boolean(addForm.value.id))
// 提交数据
const handleAddOrUpdate = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    btnLoading.value = true
    try {
      addForm.value.avatar = await avatarRef.value.getImgUrl()
      // 判断是添加或修改
      if (isAdd.value) {
        await addAdminAPI(addForm.value)
      } else {
        await updateAdminAPI(addForm.value)
      }
      ElMessage.success((isAdd.value ? '添加' : '编辑') + '成功')
      dialogVisible.value = false
      getData()
    } finally {
      btnLoading.value = false
    }
  })
}

// 分配角色
const btnRoleLoading = ref(false)
const roleDialog = ref(false)
const roleList = ref([])
const selectRole = ref([]) // 选中的角色
const uid = ref(null)
// 获取角色列表
const getRoleList = async () => {
  const res = await getRoleListAPI()
  roleList.value = res
}
// 获取用户对应的角色
const handleRole = (row) => {
  roleDialog.value = true
  uid.value = row.id
  getRoleList()
  selectRole.value = row.roles.map((item) => item.id)
}
// 提交角色
const handleSubmitRole = async () => {
  btnRoleLoading.value = true
  try {
    if (!selectRole.value.length) return ElMessage.warning('请选择角色')
    await updateUserRoleAPI({ uid: uid.value, rid: selectRole.value.join(',') })
    roleDialog.value = false
    ElMessage.success('分配成功')
    getData()
  } finally {
    btnRoleLoading.value = false
  }
}
const handleRoleClosed = () => {
  selectRole.value = []
  uid.value = null
}
</script>

<template>
  <layout-card>
    <!-- 搜索区域 -->
    <el-form class="search-container" :model="params" inline>
      <el-form-item label="用户名:">
        <el-input v-model="params.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="类型:">
        <el-select class="select" v-model="params.type" placeholder="选择类型">
          <el-option label="全部" :value="0" />
          <el-option label="管理员" :value="1" />
          <el-option label="超级管理员" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item class="search-btn">
        <el-button type="primary" @click="handleSearch" icon="Search">搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作区域 -->
    <div class="handle-container">
      <el-button v-permission="'admin:list:register'" type="primary" @click="handleAdd"
        >添加管理员</el-button
      >
      <el-button v-permission="'admin:list:updateAdminUser'" @click="handleBatchDelete"
        >批量删除</el-button
      >
    </div>
    <!-- 表格区域 -->
    <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55" :index="handleIndex" />
      <el-table-column label="用户名" prop="username" show-overflow-tooltip />
      <el-table-column label="头像">
        <template #default="{ row }">
          <zy-avatar :url="row.avatar" width="40px" height="40px" radius="3px" preview-teleported />
        </template>
      </el-table-column>
      <el-table-column label="类型">
        <template #default="{ row }">
          <el-tag :type="row.type === 1 ? 'success' : 'primary'" effect="plain">{{
            row.type === 1 ? '管理员' : '超级管理员'
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="角色">
        <template #default="{ row }">
          <el-tag
            class="role-tag"
            v-for="item in row.roles"
            :key="item.role_name"
            type="primary"
            effect="plain"
            >{{ item.role_name }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="注册时间" prop="created_time" width="180" />
      <el-table-column label="操作" fixed="right" width="180">
        <template #default="{ row }">
          <el-button
            v-permission="'admin:list:createUserRole'"
            type="primary"
            link
            @click="handleRole(row)"
            >分配角色</el-button
          >
          <el-button
            v-permission="'admin:list:updateAdminUser'"
            type="primary"
            link
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-popconfirm title="确定要删除此条数据吗？" @confirm="handleDelete(row)">
            <template #reference>
              <el-button
                v-permission="'admin:list:deleteAdminUser'"
                :loading="row.btnLoading"
                type="primary"
                link
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="params.page"
        v-model:page-size="params.pageSize"
        :page-sizes="[10, 50, 80, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSearch"
        @current-change="getData"
      />
    </div>
    <!-- 弹窗 -->
    <el-dialog
      :title="(isAdd ? '添加' : '编辑') + '管理员'"
      v-model="dialogVisible"
      align-center
      width="420px"
    >
      <!-- 表单 -->
      <el-form
        class="dialog-form"
        ref="formRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="65px"
      >
        <!-- 添加 -->
        <template v-if="isAdd">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" type="password" show-password />
          </el-form-item>
        </template>
        <el-form-item label="头像">
          <zy-upload-avatar ref="avatarRef" :url="addForm.avatar" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="addForm.type" placeholder="选择类型" style="width: 130px">
            <el-option label="管理员" :value="1" />
            <el-option label="超级管理员" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="handleAddOrUpdate">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      v-model="roleDialog"
      align-center
      width="420px"
      @closed="handleRoleClosed"
    >
      <el-select v-model="selectRole" multiple placeholder="选择角色">
        <el-option
          v-for="item in roleList"
          :key="item.id"
          :label="item.role_name"
          :value="item.id"
        />
      </el-select>
      <template #footer>
        <el-button @click="roleDialog = false">取 消</el-button>
        <el-button :loading="btnRoleLoading" type="primary" @click="handleSubmitRole"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </layout-card>
</template>

<style lang="scss" scoped>
.search-container {
  .el-form-item {
    margin-bottom: 10px;
    .select {
      width: 130px;
    }
    &.search-btn {
      margin-right: 0;
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: end;
}
.role-tag {
  margin-right: 5px;
  &:last-child {
    margin-right: 0;
  }
}
</style>
